﻿using System;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using HKEA.CMS.Core.BLL;
using HKEA.CMS.Core.Models;
using HKEA.CMS.Core.Utility;
using HKEA.CMS.Core.BLL.Tbl;
using HKEA.CMS.Core.BLL.Mtbl;
using System.Web.UI.WebControls;

namespace WebApplication
{
    public partial class Basicinformation : BasePage//System.Web.UI.Page
    {
        #region 添加两个静态变量,除非重新复制,否则不改变值,用于对比最新的值是否有变动
        private static tblCustomer staticEnt;
        private static string oldMedia;
        #endregion
        private  tblCustomer  ent = new tblCustomer(); //全局实体        
        private  tblCustomerBLL bll = tblCustomerBLL.GetInstance();
        protected string CustUID = string.Empty;

        //protected string CustIDListToJS=string.Empty;

        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                BindControl_level2();
            }
        }

        private void BindControl_level1()
        {
           IList<mtblCustType> listCustType = new List<mtblCustType>();
           mtblCustTypebBLL bllCustType = mtblCustTypebBLL.GetInstance();
           listCustType = bllCustType.GetListByENT(new mtblCustType());

           ddlCustomerType.DataSource = listCustType;
           ddlCustomerType.DataTextField = "CustType_eng"; ddlCustomerType.DataValueField = "CustTypeUID";
           ddlCustomerType.DataBind();

           ddlCustomerType.Items.Insert(0, string.Empty);
        }

        private void BindControl_level2()
        {
            BindControl_level1();
            //建议不要直接使用Request[]提取信息 服务器会依次检索所有的QueryString、Form、Cookies...            
            string code=Request.QueryString[Constant.UrlParamName.CustomerUID];
            if (!string.IsNullOrEmpty(code))  // update action
            {
                ent=new tblCustomer();
                ent.CustomerUID = int.Parse(code);
                ent = bll.GetEntity(ent);
                GetForm(ent);
                CustUID = ent.CustomerUID.ToString();
                BindMediaRoom(int.Parse(CustUID));
            }
            else//add action
            {
                //初始化控件 一般是清除文本
                usermeg.Visible = false;
                CleanText();
                //GeneratorCustomerID();//生成CustomerID
            }

            //CustIDListToJS = CustomerIDListToJS();
        }

        /// <summary>
        /// 获取 实体的值 赋给 控件
        /// </summary>
        /// <param name="entCustomer"></param>
        private void GetForm(tblCustomer entCustomer)
        {
            staticEnt = new tblCustomer();
            if (entCustomer != null)
            {
                staticEnt = entCustomer; //赋值静态变量
                txtCustomerSince.Text = entCustomer.CustomerSince == null ? "" : ((DateTime)entCustomer.CustomerSince).ToString("MMM yyyy", new CultureInfo("en-US"));
                ddlCustomerType.SelectedValue = entCustomer.CustTypeUID.ToString();
                txtCustomerID.Text = entCustomer.CustomerID;
                txtCustomerName_en.Text = entCustomer.Name_Eng;
                txtCustomerName_hk.Text = entCustomer.Name_Chi;

                txtStroke.Text = entCustomer.Stroke.ToString();
                txtYearEstablished.Text = entCustomer.EstDate == null ? "" : DateTime.Parse(entCustomer.EstDate.ToString()).ToString("yyyy", new CultureInfo("en-US")); //DateFormat(entCustomer.EstDate);
                txtNo_ofEmployee.Text = entCustomer.NoOfEmp.ToString();

                txtBR.Text = entCustomer.BR;
                //txtHKID_PassportNo.Text = entCustomer.HKID_PassportNo;
                hfHKID_PassprotNo.Value = entCustomer.HKID_PassportNo;

                if (entCustomer.EntryDate != null && ((DateTime)entCustomer.EntryDate).ToShortDateString() != DateTime.MaxValue.ToShortDateString())
                    txtMembershipSince.Text = ((DateTime)entCustomer.EntryDate).ToString("MMM yyyy", new CultureInfo("en-US")); 

                //txtMembershipSince.Text =entCustomer.EntryDate==null?"": ((DateTime)entCustomer.EntryDate).ToString("MMM yyyy", new CultureInfo("en-US"));
                txtReferralBy.Text = entCustomer.ReferralBy;
                if (entCustomer.ReferralDate != null && DateTime.Parse(entCustomer.ReferralDate.ToString()).ToShortDateString() != DateTime.MaxValue.ToShortDateString())
                {
                    txtReferralDate.Text = DateTime.Parse(entCustomer.ReferralDate.ToString()).ToString("MMM yyyy", new CultureInfo("en-US")); 
                }
                     //DateFormat(entCustomer.ReferralDate);
                cbGC.Checked = IsCheck(entCustomer.IsGCMember);
                cbHQLocatedInHK.Checked = IsCheck(entCustomer.HQLocatedinHK);
                cbVIP.Checked = IsCheck(entCustomer.IsVIP); 

                txtIntro_en.Text = entCustomer.Intro_Eng;
                txtIntro_hk.Text = entCustomer.Intro_Chi;

                BindLogoForCustomer(entCustomer.CustomerUID);//绑定该Customer的Logo
            }
        }

        private void BindMediaRoom(int custUID)
        {
            List<tblMediaRoom> list = new List<tblMediaRoom>();
            tblMediaRoom ent = new tblMediaRoom();
            ent.CustomerUID = custUID; ent.IsPublish = Constant.IsDelete.yes;
            ent.MediaType = Constant.MediaType.image;
            ent.Category = Constant.MediaRoomCategory.customer_logo;
            list = tblMediaRoomBLL.GetInstance().GetListByENT(ent);

            rp_mediaroom.DataSource = list;
            rp_mediaroom.DataBind();
        }

        private List<Ext_MediaRoom> BindMediaRoomRelated(int customerUID)
        {
            List<Ext_MediaRoom> list = new List<Ext_MediaRoom>();
            Ext_MediaRoom ent = new Ext_MediaRoom();
            ent.RelatedUID = customerUID; ent.Is_Publish = Constant.IsPublish.yes;
            ent.MediaType = Constant.MediaType.image;
            ent.Category = Constant.MediaRoomCategory.customer_logo;
            list = tblMediaRoomRelatedBLL.GetInstance().GetListWithMediaRoomByENT(ent);

            return list;
        }

        private void BindLogoForCustomer(int customerUID)
        {
            if (customerUID > 0)
            {
                List<Ext_MediaRoom>  list = BindMediaRoomRelated(customerUID);
                rpLogo.DataSource = list;
                rpLogo.DataBind();

                hfnotbind_media.Value = "";
                //辅助变量
                for (int i = 0; i < list.Count(); i++)
                {
                    hfnotbind_media.Value += list[i].MediaRoomUID.ToString() + ",";
                }
                Oldhfnotbind_media.Value = hfnotbind_media.Value;
            }
        }

        /// <summary>
        /// 获取控件的值赋给实体 保存
        /// </summary>
        private tblCustomer SetForm(tblCustomer entCustomer)
        {
            entCustomer.CustomerSince = DateFormat(txtCustomerSince.Text.Trim());
            entCustomer.CustTypeUID = int.Parse(ddlCustomerType.SelectedValue);

            string customerid_str = GeneratorCustomerID(ent.CustomerSince.ToString(), ent.CustTypeUID.ToString());//生成customer id
            entCustomer.CustomerID = customerid_str;
            txtCustomerID.Text = customerid_str;

            entCustomer.Name_Eng = txtCustomerName_en.Text.Trim();
            entCustomer.Name_Chi = txtCustomerName_hk.Text.Trim();
            entCustomer.Stroke = int.Parse(txtStroke.Text.Trim());
            entCustomer.EstDate = DateFormat(txtYearEstablished.Text+"-01-01");
            entCustomer.NoOfEmp = !string.IsNullOrEmpty(txtNo_ofEmployee.Text.Trim()) ? decimal.Parse(txtNo_ofEmployee.Text.Trim()) : 0; 
            entCustomer.BR = txtBR.Text.Trim();
            entCustomer.HKID_PassportNo = hfHKID_PassprotNo.Value;//txtHKID_PassportNo.Text.Trim();

            DateTime entryDate=new DateTime();
            if (!DateTime.TryParse(txtMembershipSince.Text, out entryDate))
            {
                entryDate = DateTime.MaxValue;
            }
            entCustomer.EntryDate = entryDate;

            DateTime referraldateVal;
            if (!DateTime.TryParse(txtReferralDate.Text, out referraldateVal))
            {
                referraldateVal = DateTime.MaxValue;
            }
            entCustomer.ReferralDate = referraldateVal;

            entCustomer.ReferralBy = txtReferralBy.Text.Trim();
            entCustomer.IsGCMember = IsCheck(cbGC.Checked);
            entCustomer.HQLocatedinHK = IsCheck(cbHQLocatedInHK.Checked);
            entCustomer.IsVIP = IsCheck(cbVIP.Checked);
            entCustomer.Intro_Eng =hfTxtIntro_en.Value.Trim(); //txtIntro_en.Text.Trim();
            entCustomer.Intro_Chi = hfTxtIntro_hk.Value.Trim();//txtIntro_hk.Text.Trim();            
            return entCustomer;
        }

        private void CleanText()
        {
            ddlCustomerType.Text = txtCustomerID.Text = txtCustomerName_en.Text = txtCustomerName_hk.Text =
                    txtNo_ofEmployee.Text = txtBR.Text = txtHKID_PassportNo.Text =hfHKID_PassprotNo.Value= txtMembershipSince.Text = txtReferralBy.Text =
                    txtIntro_en.Text = txtIntro_hk.Text = string.Empty;
            cbGC.Checked = cbGC.Checked = cbGC.Checked = false;
            txtCustomerSince.Text = txtYearEstablished.Text = txtMembershipSince.Text = DateFormat(DateTime.Now);

            //txtReferralDate.Text = DateTime.Now.ToString("MMM yyyy", new CultureInfo("en-US"));
            ddlCustomerType.SelectedIndex = 0;
        }

        /// <summary>
        /// 保存按钮事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void btnSave_Click(object sender, EventArgs e)
        {
            
            string msg = string.Empty;
            string code = Request.QueryString[Constant.UrlParamName.CustomerUID];
            if (!string.IsNullOrEmpty(code))//update action
            {
                ent = new tblCustomer();
                ent.CustomerUID = int.Parse(code);
                ent = bll.GetEntity(ent);
                ent = SetForm(ent);

                int ret = bll.UpDateENT(ent);

                SaveMediaRelated(ent.CustomerUID);//保存mediaroomrelated
                WriteToLog(false);//写入log
                if (ret > 0)
                {
                    BindLogoForCustomer(ent.CustomerUID);
                    msg = ResourceManage.GetResourceString("msg100005");
                }
                else
                    msg = ResourceManage.GetResourceString("msg100003");
            }
            else//add action
            {
                staticEnt = new tblCustomer();
                ent = new tblCustomer();               
                ent = SetForm(ent);

                ent.LastModifyBy = Session[Constant.SessionName.Manage] == null ? "system" : (Session[Constant.SessionName.Manage] as tblUser).User_Name.Trim(); 
                ent.AddressUID = new tblAddressBLL().InsertENT(new tblAddress());
                ent.ContactInfoUID = new tblContactInfoBLL().InsertENT(new tblContactInfo());
                int ret = bll.InsertENT(ent);

                SaveMediaRelated(ent.CustomerUID);//保存mediaroomrelated
                if (ret > 0)
                {
                    msg = ResourceManage.GetResourceString("msg100004");
                    Response.Redirect("~/Basicinformation.aspx?" + Constant.UrlParamName.CustomerUID + "=" + ret.ToString());
                }
                else
                    msg = ResourceManage.GetResourceString("msg100003");
            }
            lblMessages.Text = msg;
        }

        private void SaveMediaRelated(int customerUID)
        {
            tblMediaRoomRelatedBLL bll = new tblMediaRoomRelatedBLL();
            List<int> listMediaRoomUID = GetMediaRoomUIDlist();
            tblMediaRoom_Related ent = new tblMediaRoom_Related();
            ent.RelatedUID = customerUID;
            ent.Category = Constant.MediaRoomCategory.customer_logo;
            ent.Deleted = -1;

            IList<tblMediaRoom_Related> listtblMediaRoom_Related = bll.GetListByENT(ent);
            for (int i = 0; i < listtblMediaRoom_Related.Count(); i++)
            {
                bll.DeleteENT(listtblMediaRoom_Related[i]);
            }

            bll.InsertList(listMediaRoomUID, Constant.MediaRoomCategory.customer_logo, customerUID);
        }

        private List<int> GetMediaRoomUIDlist()
        {
            List<int> list = new List<int>();
            List<string>var1 = hfnotbind_media.Value.Split(',').ToList();

            for (int i = 0; i < var1.Count(); i++)
            {
                if (!string.IsNullOrEmpty(var1[i]))
                    list.Add(int.Parse(var1[i]));
            }
            return list;
        }

        #region 内置方法
        
        /// <summary>
        /// 整数转换成布尔型    0=>false ; 1=>true
        /// </summary>
        /// <param name="value">整数 1,0</param>
        /// <returns>布尔值true,false</returns>
        private bool IsCheck(object value)
        {
            int temp = 0; int.TryParse(value.ToString(), out temp); return temp == 0 ? false : true;
        }

        /// <summary>
        /// 布尔型转换成整数   false=>0 ; true=>1
        /// </summary>
        /// <param name="value">布尔值true,false</param>
        /// <returns>整数 1,0</returns>
        private int IsCheck(bool value)
        {
            return value ? 1 : 0;
        }
        
        #endregion

        /// <summary>
        /// 生成CustomerID字符串
        /// </summary>
        /// <param name="entCustomer">Custmer实体</param>
        /// <param name="cust_since"></param>
        /// <param name="cust_type"></param>
        /// <returns>CustomerID字符串</returns>
        private string GeneratorCustomerID(string cust_since,string cust_type)
        {
            string ret = string.Empty;
            tbCodeGeneratorBLL bllCodeGenerator = new tbCodeGeneratorBLL();
            mtblCustTypebBLL bllCustType = mtblCustTypebBLL.GetInstance();
            string cuid = Request.QueryString[Constant.UrlParamName.CustomerUID];
            if (!string.IsNullOrEmpty(cust_since) && !string.IsNullOrEmpty(cust_type)&&!string.IsNullOrEmpty(cuid))
            {
                DateTime dt_cust_since = DateFormat(cust_since); 
                int int_cut_type = int.Parse(cust_type);
                tblCustomer entCustomer = tblCustomerBLL.GetInstance().GetEntity(int.Parse(cuid));

                if (entCustomer != null)
                {
                    if (entCustomer.CustomerSince != dt_cust_since || entCustomer.CustTypeUID != int_cut_type)//customer since 或者type 有改变时
                    {
                        mtblCustType entCustType = bllCustType.GetEntity(int_cut_type);
                        string custTypePrefix = entCustType == null ? string.Empty : entCustType.Prefix;
                        ret = bllCodeGenerator.BuilderCustomerCode(custTypePrefix, dt_cust_since);
                    }
                    else
                    {
                        if (string.IsNullOrEmpty(entCustomer.CustomerID))
                        {
                            mtblCustType entCustType = bllCustType.GetEntity(int_cut_type);
                            string custTypePrefix = entCustType == null ? string.Empty : entCustType.Prefix;
                            ret = bllCodeGenerator.BuilderCustomerCode(custTypePrefix, dt_cust_since);
                        }
                        else
                        {
                            ret = entCustomer.CustomerID;
                        }
                    }
                }
                else
                {
                    mtblCustType entCustType = bllCustType.GetEntity(int_cut_type);
                    string custTypePrefix = entCustType == null ? string.Empty : entCustType.Prefix;
                    ret = bllCodeGenerator.BuilderCustomerCode(custTypePrefix, dt_cust_since);
                }
            }
            return ret;
        }

        public string CustomerIDListToJS()
        {
            string ret = "";
            List<tblCustomer> CustList = null;
            if (Session["custid_autoComplete"] == null)
            {
                tblCustomerBLL bllCust = new tblCustomerBLL();
                tblCustomer entCust = new tblCustomer();
                CustList = new List<tblCustomer>();

                entCust.Deleted = 0;
                CustList = bllCust.GetListByENT(entCust);//File.ReadAllLines(Server.MapPath("~/App_Data/TextFile.txt"));
                
            }
            else
                CustList = Session["custid_autoComplete"] as List<tblCustomer>;

            for (int i = 0; i < CustList.Count(); i++)
                ret += CustList[i].CustomerID.Trim() + "&";

            return ret;
        }

        private void WriteToLog(bool _bool) 
        {
            string ChangeList = string.Empty;
            if (staticEnt != null)
            {
                string _customerSince = staticEnt.CustomerSince == null ? "" : ((DateTime)staticEnt.CustomerSince).ToString("MMM yyyy", new CultureInfo("en-US"));
                if (txtCustomerSince.Text != _customerSince)
                {
                    ChangeList += ", CustomerSince change to :" + txtCustomerSince.Text;
                }
                if (ddlCustomerType.SelectedValue != staticEnt.CustTypeUID.ToString())
                {

                    ChangeList += ", CustomerTyp change to :" + ddlCustomerType.SelectedItem.Text;
                }
                if (txtCustomerName_en.Text != staticEnt.Name_Eng)
                {
                    ChangeList += ", CustomerName change to :" + txtCustomerName_en.Text;
                }
                if (txtCustomerName_hk.Text != staticEnt.Name_Chi)
                {
                    ChangeList += ", 客戶名稱 change to :" + txtCustomerName_hk.Text;
                }
                if (txtStroke.Text != staticEnt.Stroke.ToString())
                {
                    ChangeList += ", Stroke change to :" + txtStroke.Text;
                }
                string _estDate = staticEnt.EstDate == null ? "" : DateTime.Parse(staticEnt.EstDate.ToString()).ToString("yyyy", new CultureInfo("en-US"));
                if (txtYearEstablished.Text != _estDate)
                {
                    ChangeList += ", YearEstablished change to :" + txtYearEstablished.Text;
                }
                if (txtNo_ofEmployee.Text != staticEnt.NoOfEmp.ToString())
                {
                    ChangeList += ", No_ofEmployee change to :" + txtNo_ofEmployee.Text;
                }
                if (txtBR.Text != staticEnt.BR)
                {
                    ChangeList += ", BR change to :" + txtBR.Text;
                }
                if (hfHKID_PassprotNo.Value != staticEnt.HKID_PassportNo)
                {
                    ChangeList += ", HKID_PassprotNo change to :" + hfHKID_PassprotNo.Value;
                }
                if (staticEnt.EntryDate != null && ((DateTime)staticEnt.EntryDate).ToShortDateString() != DateTime.MaxValue.ToShortDateString())
                {
                    string _entryDate;
                    _entryDate = ((DateTime)staticEnt.EntryDate).ToString("MMM yyyy", new CultureInfo("en-US"));
                    if (txtMembershipSince.Text != _entryDate)
                    {
                        ChangeList += ", EntryDate change to :" + txtMembershipSince.Text;
                    }
                }
                if (txtReferralBy.Text != staticEnt.ReferralBy)
                {
                    ChangeList += ", ReferralBy change to :" + txtReferralBy.Text;
                }
                if (staticEnt.ReferralDate != null && DateTime.Parse(staticEnt.ReferralDate.ToString()).ToShortDateString() != DateTime.MaxValue.ToShortDateString())
                {
                    string _referralDate;
                    _referralDate = DateTime.Parse(staticEnt.ReferralDate.ToString()).ToString("MMM yyyy", new CultureInfo("en-US"));
                    if (txtReferralDate.Text != _referralDate)
                    {
                        ChangeList += ", ReferralDate change to :" + txtReferralDate.Text;
                    }
                }

                if (cbGC.Checked != IsCheck(staticEnt.IsGCMember))
                {
                    ChangeList += ", GC change to :" + IsCheck(cbGC.Checked);
                }
                if (cbHQLocatedInHK.Checked != IsCheck(staticEnt.HQLocatedinHK))
                {
                    ChangeList += ", HQLocatedInHK change to :" + IsCheck(cbHQLocatedInHK.Checked);
                }
                if (cbVIP.Checked != IsCheck(staticEnt.IsVIP))
                {
                    ChangeList += ", VIP change to :" + IsCheck(cbVIP.Checked);
                }
                if (txtIntro_en.Text != staticEnt.Intro_Eng)
                {
                    ChangeList += ", Intro_en change to :" + txtIntro_en.Text;
                }
                if (txtIntro_hk.Text != staticEnt.Intro_Chi)
                {
                    ChangeList += ", 簡介 change to :" + txtIntro_hk.Text;
                }
                if (Convert.ToInt32(tempVal.Value) == 1)
                {
                    ChangeList += ", Logo / Trademark have been change";
                }
                if (_bool) {
                    ChangeList = ChangeList.Replace("change","add");
                }

                BasePage _Base = new BasePage();
                tblUser ent = _Base.GetManageFromSession();

                Literal CompanyName = usermeg.FindControl("ltlCompanyName_eng") as Literal;
                tblHistory entlog = new tblHistory();
                entlog.HistoryCatUID = 1;
                entlog.HistoryTypeUID = 24;
                entlog.CustomerUID = staticEnt.CustomerUID;
                entlog.Cust_MemberUID = 0;
                entlog.ContactPersonUID = 0;
                entlog.History_Detail = ent.User_Name + "{" + CompanyName.Text + "}{Basicinformation}" + ChangeList;
                entlog.LastModifyBy = ent.User_Name;
                if (ChangeList.Length - 1 > 0)
                {
                    int tal = tblHistoryBLL.GetInstance().InsertENT(entlog);
                }
            }
        }
    }
}